package net.chrisrichardson.ec2deployer.applications

import net.chrisrichardson.ec2deployer.core.Application
import net.chrisrichardson.ec2deployer.cluster.ClusterSpec
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.cluster.DatabaseTier
import net.chrisrichardson.ec2deployer.cluster.TerracottaTier
import net.chrisrichardson.ec2deployer.cluster.WebServerTier

abstract class AbstractApplicationServer extends Application implements ApplicationServer  {

    static int counter;
    String jvmRoute
    int port = 8080
    TerracottaTier terracottaTier
    DatabaseTier databaseTier

    ClusterSpec clusterSpec
    WebServerTier webServerTier

    protected AbstractApplicationServer() {}
    
    public AbstractApplicationServer(ClusterSpec clusterSpec, EC2Server host, DatabaseTier databaseTier, TerracottaTier terracottaTier, WebServerTier webServerTier) {
		super(host)
        this.clusterSpec = clusterSpec
        addRequiredApplication(databaseTier.databaseServer)
		this.jvmRoute = "tomcat" + counter++
        this.databaseTier = databaseTier
        this.terracottaTier = terracottaTier
        this.webServerTier = webServerTier
    }

    List<WebApp> getWebApps() {
        clusterSpec.webApps
    }

    def makeCatalinaOpts() {
        def optionsBuilder = new CatalinaOptionsBuilder()
        optionsBuilder.webServerTier = webServerTier
        terracottaTier.addToCatalinaOpts(optionsBuilder)
        clusterSpec.catalinaOptsBuilderAsClosure.call(optionsBuilder, databaseTier.databaseServerDnsName, databaseTier.mySqlSlavesDnsName)
        optionsBuilder.options
    }

    void waitUntilRunning() {
        waitForHttp port: 8080, path: clusterSpec.webApps[0].actualContext
    }

    def getContexts() {
        webApps.context
    }

    def getActualContexts() {
        webApps.actualContext
    }

    
}